<template>
  <div id="labmaininfo" style="height: 100%">
    <div class="bodyContent">
      <vxe-toolbar perfect>
        <template #buttons>
          <span class="padding-right-xs">报告单元</span>
          <SelectWorkGroup :url="'/api/rptGroup/findRptGroupList'" :businessType="'30'" @getSelectedId="getSelectedId"></SelectWorkGroup>
          <span v-for="(item, index) in labmaininfobtns" :key="index" class="padding-lr-xs">
            <vxe-button v-if="item.type === 0" type="text" class="button-blue" :icon="item.icon" :content="item.content" @click="actionCLick(item)"></vxe-button>
            <span v-if="item.type === 1">
              <vxe-button v-for="(val, idx) in item.children" :key="idx" type="text" class="button-blue" :icon="val.position === 'left' ? val.icon : ''" @click="actionCLick(val)">
                {{ val.content }}
                <i v-if="val.position === 'right'" :class="val.icon"></i>
              </vxe-button>
            </span>
            <vxe-button v-if="!isVisiableFChkBtn && item.type === 3 && item.name && item.name === 'firstReviewed' && (currentMainInfo.isChk < 1 || currentMainInfo.isChk === null)" type="text" class="button-blue" content="初审" @click="actionCLick(item.children[0])"></vxe-button>
            <vxe-button v-if="!isVisiableFChkBtn && item.type === 3 && item.name && item.name === 'firstReviewed' && currentMainInfo.isChk == 1" type="text" class="button-red" content="取消初审" @click="actionCLick(item.children[1])"></vxe-button>
            <vxe-button v-if="item.type === 3 && item.name && item.name === 'reviewed' && (currentMainInfo.isChk < 2 || currentMainInfo.isChk === null)" type="text" class="button-blue" content="审核" @click="actionCLick(item.children[0])"></vxe-button>
            <vxe-button v-if="item.type === 3 && item.name && item.name === 'reviewed' && currentMainInfo.isChk == 2" type="text" class="button-red" content="取消审核" @click="actionCLick(item.children[1])"></vxe-button>
            <vxe-button v-if="item.type === 5 && dzblBtnText !== ''" type="text" class="button-blue" :icon="item.icon" :content="dzblBtnText" @click="actionCLick(item)"></vxe-button>
          </span>
        </template>
        <template #tools>
          <!-- <vxe-button type="text" class="button-blue" icon="vxe-icon-square-fill" content="自动审核"></vxe-button> -->
          <vxe-button class="button-blue" icon="vxe-icon-setting-fill" @click="wkltConfig" v-if="isShowSettingBtn"></vxe-button>
        </template>
      </vxe-toolbar>
      <div class="area margin-top-xs">
        <Splitpanes class="Splitpanes" :dbl-click-splitter="false">
          <Pane :size="patInfoPanelSize">
            <Splitpanes horizontal :dbl-click-splitter="false">
              <Pane size="88">
                <vxe-toolbar class-name="bg-grey light" :className="notCurDay ? 'bg-yellow light' : 'bg-grey light'">
                  <template #buttons>
                    <div class="padding-lr-xs">
                      <vxe-form ref="xFormBase" class-name="bg-grey light" :className="notCurDay ? 'bg-yellow light' : 'bg-grey light'" title-align="left" title-width="60" :data="form">
                        <vxe-form-item title="检验日期" span="24" field="sampleda">
                          <template #default="{ data }">
                            <vxe-input v-model="data.sampleda" type="date" :value-format="'yyyy-MM-dd'" :label-format="'yyyy-MM-dd'" transfer @change="timeChange"></vxe-input>
                          </template>
                        </vxe-form-item>
                        <vxe-form-item title="标本号" span="24" field="sampleNo">
                          <template #default="{ data }">
                            <vxe-input ref="codeInput" :class="() => { }" v-model="data.sampleNo" clearable @keydown="handleSearchByCode" @blur="handleSearchByCode" @focus="() => { }"></vxe-input>
                          </template>
                        </vxe-form-item>
                        <vxe-form-item title="条码号" span="24" field="reqNo">
                          <template #default="{ data }">
                            <vxe-input ref="reqNoInput" :class="() => { }" lang="en-US" v-model="data.reqNo" :disabled="form.isChk === 1 || form.isChk === 2" clearable @input="(params) => { }" @keydown="handleSearchByReqno"></vxe-input>
                            <!--  -->
                          </template>
                        </vxe-form-item>
                      </vxe-form>
                    </div>
                  </template>
                </vxe-toolbar>
                <MainInfoEditPanel ref="mainInfoEditPanelRef" :currentMainInfoObj="currentMainInfo" @UpdateSuccessCallback="mainInfoUpdateSuccessCallback" @validateTestChkDoctorSuccess="validateTestChkDoctorSuccess" @onlyRefreshRptResult="refreshRptresultsAfterChangeReferConds1" />
              </Pane>
              <Pane size="12">
                <div class="padding-lr-xs left-bottom-status-panel">
                  <vxe-toolbar>
                    <template #buttons>
                      <span class="text-bold">状态:</span>
                      <span class="padding-lr-xs">{{ chkStatus }}</span>
                      <span class="padding-lr-xs">{{ isPrinted }}</span>
                    </template>
                    <template #tools v-if="isTipsExistAlarm">
                      <span class="text-bold text-red margin-right-xs">有未处理危急值</span>
                    </template>
                  </vxe-toolbar>
                  <vxe-toolbar>
                    <template #buttons>
                      <span class="text-bold">收费:</span>
                      <span class="padding-lr-xs">已收费</span>
                    </template>
                    <template #tools>
                      <span class="text-bold">总金额:</span>
                      <span class="padding-lr-xs text-price">{{ costTotal }}</span>
                    </template>
                  </vxe-toolbar>
                  <vxe-toolbar>
                    <template #buttons>
                      <div class="flex justify-start text">
                        <span class="text-bold">检验医师:</span>
                        <span class="padding-lr-xs text-shadow text-bold text-orange">{{ testChkDoctorObj.testDoctorNa }}</span>
                        <!-- <span class="padding-lr-xs">{{currentMainInfo.testDoctorNa}}</span> -->
                      </div>
                    </template>
                    <template #tools>
                      <div class="flex justify-start text">
                        <span class="text-bold">审核医师:</span>
                        <span class="padding-lr-xs text-shadow text-bold text-orange">{{ testChkDoctorObj.chkDoctorNa }}</span>
                        <!-- <span class="padding-lr-xs">{{currentMainInfo.chkDoctorNa}}</span> -->
                      </div>
                    </template>
                  </vxe-toolbar>
                  <vxe-toolbar>
                    <template #buttons>
                      <div class="flex justify-start text" v-if="criRptTredList.length>0">
                        <span class="text-red text-bold text-shadow">{{`${criRptTredList[0].treatmentMeasure} ${criRptTredList[0].reviewerTime}`}}</span>
                      </div>
                    </template>
                  </vxe-toolbar>
                </div>
              </Pane>
            </Splitpanes>
          </Pane>
          <Pane :size="resultSize">
            <el-tabs class="lab-maininfo-right-tab el-tab-sm" type="border-card" v-model="activetab">
              <el-tab-pane label="图像" name="imgTab"  >
                <ImageSelect ref="imgSelectRef" @getRptResult="rptResultList" @updateTestList="updateTestList" @pushTemplate="pushTemplate" />
              </el-tab-pane>
              <el-tab-pane label="报告" name="textTab"  >
                <ImgTxtRptForm ref='imgTxtRptRef' @updateTestList="updateTestList" ></ImgTxtRptForm>
              </el-tab-pane>
              <el-tab-pane label="历史报告" name="hislistTab" style='height: 100vh'>
                <template #label>
                  <el-badge :is-dot="isDot">
                    <span>历史报告</span>
                  </el-badge>
                </template>
                <GeneralReview ref="generalReviewRef" @getIsDot="getIsDot" />
              </el-tab-pane>
            </el-tabs>
          </Pane>
          <Pane :size="patInfoFieldSize">
            <el-tabs v-model="rightTabValue" class="lab-maininfo-right-tab el-tab-sm" type="border-card" @tab-click="templateClick">
              <el-tab-pane name="0" label="列表">
                <Splitpanes horizontal>
                  <Pane :size="mainInfoTopPanel">
                    <TestList ref="refFormData" :formObj="form"
                              @quietRefreshRptresult="refreshRptresultsAfterChangeReferConds"
                              @getReqRptResult="reqRptResult"
                              @getLabMainInfoList="labMainInfoList"
                              @mainInfoRowChange="mainInfoRowChange"
                              @printAfterChk="printAfterChk"
                              @tipsAlarmExist="tipsAlarmExist"
                              @onlyUpdatePatResultInfo="onlyUpdatePatResultInfo"
                              @auditGetNextRow="auditGetNextRow" />
                  </Pane>
                  <Pane :size="100 - mainInfoTopPanel">
                    <Template ref="miTemplateRef" @getResultTemplate="getResultTemplate"></Template>
                  </Pane>
                </Splitpanes>
              </el-tab-pane>
              <el-tab-pane name="3" label="结果模板">
                <Template ref="templateRef" @getResultTemplate="getResultTemplate" />
              </el-tab-pane>
              <el-tab-pane name="4" label="复查">
                <Repetition ref="repetitionRef" />
              </el-tab-pane>
            </el-tabs>
          </Pane>
        </Splitpanes>
      </div>
    </div>
    <!-- 预览报告  [{id:'1',isChecked:true,reportObjectCode:'XXXXX生化报告'},{id:'2',isChecked:false,reportObjectCode:'XXXXX免疫报告'}]-->
    <MultiRptPreview :reportList="reportList" :toggle="isPreviewRpt" :modalTitle="'报告预览'" />
    <!-- 批量扫码 -->
    <WkltInsertByScanCodeRef ref="scanCodeDlgRef" @refreshLabMinInfo="refreshLabMinInfo" @getLabMainInfos="getLabMainInfoTableList" />
    <!-- 危机值上报 -->
    <CriticalReport ref="criticalReportRef" @treatFinish="alarmTreatFinish" />
    <!-- 列表字段顺序控制 -->
    <WkltConfig ref="wkltConfigRef" @refreshFields="refreshFields" />
    <!-- 静默打印 -->
    <QuietPrint ref="quietPrintRef" :printParams="printParamsObj" />
    <!-- 审核密码授权 -->
    <ChkAuthComp ref="ChkAuthCompRef" @AuthSuccess="chkConfirm" />
    <!-- 授权验证组件 -->
    <AuthValidateComp ref="AuthValidateCompRef" @unChkConfirm="unChkConfirm" />
  </div>
</template>

<script lang="ts" setup>
import { reactive, ref, getCurrentInstance, onMounted, computed, watch, provide } from 'vue';
import { VXETable } from 'vxe-table';
import type { VxeTableInstance, VxeTablePropTypes, VxeTableEvents } from 'vxe-table';
import XEClipboard from 'xe-clipboard';
import { IsEmpty, formatDateTime, autoIncrementNumber } from '@/utils/common';
import { initWebSocket } from '@/utils/websocket';
import VxePulldownSelection from '@/components/VxePulldownSelection.vue';
import { LabMainInfoBtns } from './LabImgTxtRptUtils';
import { Splitpanes, Pane } from 'splitpanes';
import MainInfoEditPanel from '@/components/MainInfoEditPanel.vue';
import SampleReturn from '@/components/SampleReturn.vue';
import WkltInsertByScanCodeRef from '@/views/lab_sys/lab_bus/components/WkltInsertByScanCodeRef.vue'; //批量扫码
import CriticalReport from '@/views/lab_sys/lab_bus/components/CriticalReport.vue'; //危急值上报
import WkltConfig from '@/views/lab_sys/lab_bus/components/WkltConfig.vue'; //批量扫码
import ImgTxtRptForm from './components/mar/ImgTxtRptMarForm.vue';
import TestList from '../lab_bus/components/TestList.vue';
import ImageSelect from './components/img_txt_rpt/ImageSelect.vue';
import Template from '../lab_bus/components/Template.vue';
import Cost from '../lab_bus/components/Cost.vue';
import LabMainInfoLog from '../lab_bus/components/LabMainInfoLog.vue';
import Repetition from '../lab_bus/components/Repetition.vue';
import GeneralReview from './components/img_txt_rpt/GeneralReview.vue';
import EditForm from './components/img_txt_rpt/EditForm.vue';
import { Jh_timeStampToTime } from '@/utils/TimeUtils';
import SelectWorkGroup from '../lab_bus/components/SelectWorkGroup.vue'; //报告单元引入下拉组件
import LabMainInfoUnChkReason from '../lab_bus/components/LabMainInfoUnChkReason.vue'; /**取消审核原因 */
import { VxeMessage, VxeNotifyType } from '@/utils/CommonMessage';
import MultiRptPreview from '@/components/MultiRptPreview.vue';
import { fromPairs, isEmpty } from 'lodash';
import QuietPrint from '@/components/QuietPrint.vue';
import ChkAuthComp from '@/components/ChkAuthComp.vue';
import AuthValidateComp from '@/components/AuthValidateComp.vue'; //AuthValidateComp
import { GetRptGroupOptions } from '@/utils/SysOptionsHelper';
import { getOptionValueByCodeGlobalOption, getOptionValueByCodeRptGroupOption } from '@/utils/SysOptionsHelper';
import { AppStore } from '@/stores/store';
import { SysOptions } from '@/stores/sysoptions';
import { WebSocketStores } from '@/stores/websocketstore';
import { LocGet, LocPost } from '@/utils/LocRequestHelper';

const storeObj = AppStore();
const sysoptionObj = SysOptions(); //系统参数状态管理对象
let websocketstoreObj = WebSocketStores(); //WebSocket全局变量对象
let generalReviewRef: any = ref(null); //历史结果
let rptResultRef: any = ref(null); //报告结果传值
let templateRef: any = ref(null); //模版传值
let miTemplateRef: any = ref(null); //检验记录下方的输入模板
let costRef: any = ref(null); //费用传值
let repetitionRef: any = ref(null); //复查
let scanCodeDlgRef: any = ref(null); //批量扫码
let sampleReturnRef: any = ref(null); //不合格标本号
let LabMainInfoLogRef: any = ref(null); //操作日志
let criticalReportRef: any = ref(null); //危急值上报
let wkltConfigRef: any = ref(null); //设置
let imgTxtRptRef: any = ref(null); //图片ref
let imgSelectRef: any = ref(null); //图片ref
let patInfoPanelSize: any = ref(12); //病人信息列宽度
let resultSize: any = ref(63); //结果信息列宽度
let patInfoFieldSize: any = ref(25); //字段列表信息列宽度
let activetab: any = ref('imgTab'); //默认页签
let patInfoFieldDecimalSize: any = ref(null); //字段列表信息列宽度(小数)
let resultRowHeight: any = ref(null); //结果行高
let wlRowHeight: any = ref(null); //字段列表信息列宽度
let ChkAuthCompRef = ref(null); //审核授权弹窗对象
let AuthValidateCompRef = ref(null); //授权验证弹窗对象
let { proxy }: any = getCurrentInstance();
let $this = {} as any;
let notCurDay = ref(false);
let isDot = ref(false);
let printParamsObj = ref(null);
let chkBeforePrint = ref(false); /**是否打印前的自动审核 */
let alarmReportBeforeChk = ref(false); /**是否审核审核前上报危急值 */
let mainInfoTopPanel = ref(100); /**检验主记录列表面板 */
let isShowItemTemplatePanel = ref(false); /**是否显示项目模板面板 */
let isTipsExistAlarm = ref(false);
let isShowSettingBtn = ref(false);
let testChkDoctorObj = reactive({ testDoctor: '', testDoctorNa: '', chkDoctor: '', chkDoctorNa: '' });
let timerIntervalObj = ref(null); /**跨天提示 夜班辛苦了，是否切换当前日期 */
let timerIntervaldlgObj = ref(null); /**跨天提示 夜班辛苦了，是否切换当前日期弹窗对象 */
let rightTabValue = ref('0'); /**当前选中的页签 */
let dateDiffDialogObj = ref(null); /**本地时间服务器时间不一致提醒弹窗对象 */
let LabMainInfoUnChkReasonRef = ref(null); /**取消审核原因弹窗对象 */
let criRptTredList = reactive([]);
interface RowVO {
  id: number;
  name: string;
  nickname: string;
  role: string;
  sex: string;
  sex2: string[];
  num1: number;
  age: number;
  address: string;
  date12: string;
  date13: string;
}
const reqNoInput = ref(null); /*条码号 输入框 Ref对象*/
const isPreviewRpt = ref(false);
const labmaininfobtns = ref(LabMainInfoBtns());
const tableRef = ref<VxeTableInstance<RowVO>>();

const loading = ref(false);
const tableData = ref<RowVO[]>([]);
const quietPrintRef = ref(null); //静默打印组件

const menuConfig = reactive<VxeTablePropTypes.MenuConfig<RowVO>>({
  header: {
    options: [
      [
        { code: 'hideColumn', name: '隐藏列', disabled: false },
        { code: 'showAllColumn', name: '取消所有隐藏列', disabled: false }
      ]
    ]
  },
  body: {
    options: [
      [
        { code: 'copy', name: '复制', prefixIcon: 'vxe-icon-copy', disabled: false },
        { code: 'reload', name: '刷新', disabled: false },
        { code: 'insertAt', name: '插入', disabled: false },
        { code: 'remove', name: '删除', disabled: false },
        { code: 'save', name: '保存', prefixIcon: 'vxe-icon-save', disabled: false }
      ]
    ]
  },
  visibleMethod({ options, column }) {
    const isDisabled = !column;
    options.forEach((list) => {
      list.forEach((item) => {
        item.disabled = isDisabled;
      });
    });
    return true;
  }
});

const sexList = ref([
  { label: '', value: '' },
  { label: '男', value: '1' },
  { label: '女', value: '0' }
]);

const formatSex = (row: RowVO) => {
  if (row.sex === '1') {
    return '男';
  }
  if (row.sex === '0') {
    return '女';
  }
  return '';
};
const form = reactive({
  id: '',
  //sampleda: formatDateTime(IsEmpty(localStorage.getItem('currentDate')) ? new Date() : localStorage.getItem('currentDate'), 'yyyy-MM-dd'),
  sampleda: formatDateTime(new Date(), 'yyyy-MM-dd'),
  sampleNo: '1',
  reqNo: '',
  rptGroup: ''
});
const scanCodeForm = reactive({
  sampleNo: '1',
  visible: false,
  rptGroup: '',
  sampleda: formatDateTime(new Date(), 'yyyy-MM-dd'),
  busType: '1' /**业务类型，普通检验 */,
  wl: []
});
const wkltConfigForm = reactive({
  visible: false,
  rptGroup: '',
  rptGroupName: ''
});
let rptGroupNameSelected = ref('');
let rptGroupOptions = reactive([]);
let mainInfoEditPanelRef: any = ref(null); //回车标本号新增数据
let currentMainInfo: any = reactive({}); //当前选中上机记录
//let mainInfoData = reactive({});//选中检验主记录

//组件间共享变量
const rptImages = ref('');
provide('rptImages', rptImages);
//共享Maininfo
provide('rptMaininfo', currentMainInfo);

//#region  监听属性
watch(
  () => storeObj.chkDoctorObj,
  (n, o) => {
    if (!IsEmpty(n.code)) {
      testChkDoctorObj.chkDoctor = n.code;
    }
    if (!IsEmpty(n.name)) {
      testChkDoctorObj.chkDoctorNa = n.name;
    }
  },
  { deep: true, immediate: true }
);
watch(
  () => storeObj.testDoctorObj,
  (n, o) => {
    if (!IsEmpty(n.code)) {
      testChkDoctorObj.testDoctor = n.code;
    }
    if (!IsEmpty(n.name)) {
      testChkDoctorObj.testDoctorNa = n.name;
    }

    /**如果会话存储中没有记忆值，取当前登陆人 */
    if (IsEmpty(testChkDoctorObj.testDoctor)) {
      const locRemObj = localStorage.getItem('userInfo');
      if (!IsEmpty(locRemObj)) {
        const locRemObjEntry = JSON.parse(locRemObj);
        if (!IsEmpty(locRemObjEntry.username)) {
          testChkDoctorObj.testDoctor = locRemObjEntry.username;
        }
        if (!IsEmpty(locRemObjEntry.realname)) {
          testChkDoctorObj.testDoctorNa = locRemObjEntry.realname;
        }
      }
    }
  },
  { deep: true, immediate: true }
);
/**跨天是否切换当前日期 */
watch(
  () => websocketstoreObj.isChangeDate,
  (n, o) => {
    if (n) {
      changeCurrentDateTips();
    }
  }
);
//#endregion

//#region  计算属性
/**是否频闭初审按钮 */
let isVisiableFChkBtn = computed(() => {
  const a = sysoptionObj.globalOptions.filter((p: any) => p.field === 'ishidefirstchk');
  if (a && a.length > 0 && a[0] && !IsEmpty(a[0].value)) {
    return IsEmpty(a[0].value) ? false : a[0].value === '1' || a[0].value === 1 ? true : false;
  }
  return false;
});
/**获取费用合计 */
let costTotal = computed(() => {
  if (!currentMainInfo || IsEmpty(currentMainInfo.isChk)) {
    return '0.00';
  }
  const a = costRef.value?.getCostTotal();
  return IsEmpty(a) ? '' : a.toFixed(2);
});
/**左下角审核状态 */
let chkStatus = computed(() => {
  if (!currentMainInfo || IsEmpty(currentMainInfo.isChk)) {
    return '未审核';
  } else if (!IsEmpty(currentMainInfo.isChk) && currentMainInfo.isChk === 1) {
    return '已初审';
  } else if (!IsEmpty(currentMainInfo.isChk) && currentMainInfo.isChk === 2) {
    return '已审核';
  } else {
    return '未审核';
  }
});
/**计算属性是否打印 */
let isPrinted = computed(() => {
  if (!currentMainInfo || IsEmpty(currentMainInfo.isPrint)) {
    return '未打印';
  } else if (!IsEmpty(currentMainInfo.isPrint) && currentMainInfo.isPrint === 1) {
    return '已打印';
  } else {
    return '未打印';
  }
});
/**病历按钮显示文字(等于-时隐藏) */
let dzblBtnText = computed(() => {
  const a = sysoptionObj.globalOptions.filter((p: any) => p.field === 'blbtntxt');
  if (a && a.length > 0 && a[0] && !IsEmpty(a[0].value)) {
    return IsEmpty(a[0].value) ? '' : a[0].value === '-' ? '' : a[0].value;
  }
  return '';
});
//#endregion

// 方法定义区 =============
onMounted(() => {
  setTimeout(() => {
    /**本地时间、服务器时间不相等  提示修改时间 */
    const locpcdate = formatDateTime(new Date(), 'yyyy-MM-dd');
    const serpcdate = formatDateTime(localStorage.getItem('currentDate'), 'yyyy-MM-dd');
    if (!timerIntervaldlgObj.value && !IsEmpty(locpcdate) && !IsEmpty(serpcdate) && !dateDiffDialogObj.value && locpcdate !== serpcdate) {
      dateDiffDialogObj.value = VXETable.modal.confirm({ content: '本地时间与服务器时间不一致，请先修改时间!', title: '提醒', iconStatus: 'vxe-icon-time' });
      dateDiffDialogObj.value.then((type) => {
        if (type === 'confirm') {
        }
      });
    }

  }, 4000);

  /**解决标本合并 时间跟主界面选择时间不一致的问题 */
  localStorage.setItem('sampleDateNow', formatDateTime(form.sampleda, 'yyyy-MM-dd'));

  const a = LocPost((window as any).apiUrl.VUE_APP_LOCAL_PRINT_URL + '/api/Home/get-is-start', { a: '' }); /**验证本地打印服务是否开启 */
  a.then((b) => {
    if (b) {
      sessionStorage.setItem('locserstart', true);
    } else {
      sessionStorage.setItem('locserstart', false);
    }
  });

  const reboot = LocPost((window as any).apiUrl.VUE_APP_LOCAL_PRINT_URL + '/api/InstrumentInterfaceApp/boot', { a: '' }); /**重启仪器接口 */
  reboot.then((b) => {
    console.log('重启接口已调用', b);
  });

  if (storeObj.userInfo && storeObj.userInfo.username && storeObj.userInfo.username.includes('admin')) {
    isShowSettingBtn.value = true;
  }
  getmoduleWidth();
  // findRptGroupOptions();
  findList();
  //refFormData.value.initPage(form);
  // mainInfoEditPanelRef.value.getWkltConfigList(form.rptGroup);
  //rptResultRef.value.getResultConfigList(form.rptGroup);

  initWebSocket(getddddd);

  /**启动定时器，提示夜班辛苦了 */
  //skipCurDay();
});

/**时间来到第二天 切换日期提示 */
function skipCurDay() {
  if (timerIntervalObj.value) {
    timerIntervalObj.value = null;
  }
  timerIntervalObj.value = setInterval(() => {
    let timeStr = formatDateTime(new Date(), 'hhmmss');
    if (timeStr === '000000' && !timerIntervaldlgObj.value) {
      timerIntervaldlgObj.value = VXETable.modal.confirm({ content: '夜班辛苦了,是否切换当前日期?', title: '消息', iconStatus: 'vxe-icon-time' });
      timerIntervaldlgObj.value.then((type) => {
        if (type === 'confirm') {
          form.sampleda = formatDateTime(new Date(), 'yyyy-MM-dd');
          form.sampleNo = '1';
          proxy.$nextTick(() => {
            timeChange();
          });
          timerIntervaldlgObj.value = null;
        } else {
          timerIntervaldlgObj.value = null;
        }
      });
    }
  }, 1000);
}

/**WebSocket  推送切换当前日期 */
function changeCurrentDateTips() {
  if (timerIntervaldlgObj.value) {
    return;
  }
  timerIntervaldlgObj.value = VXETable.modal.confirm({ content: '夜班辛苦了,是否切换当前日期?', title: '温馨提示', iconStatus: 'vxe-icon-time' });
  timerIntervaldlgObj.value.then((type) => {
    if (type === 'confirm') {
      form.sampleda = formatDateTime(new Date(), 'yyyy-MM-dd');
      form.sampleNo = '1';
      proxy.$nextTick(() => {
        timeChange();
      });
      websocketstoreObj.setIsChangeDate(false);
      timerIntervaldlgObj.value = null;
    } else {
      timerIntervaldlgObj.value = null;
    }
  });
}

function getddddd(data: any) {
  //todo
}

/**组件之间调度 */
function mainInfoRowChange(row, isRefreshRptResult) {
  /**清空危急值处理信息 */
  criRptTredList.length = 0;
  isTipsExistAlarm.value = false;

  if (!row || IsEmpty(row)) {
    /**如果是条件筛选状态，直接返回，因为 上一个、下一个会处理 */
    const m = refFormData.value?.isMultiFilterState();
    if (m) {
      return;
    }

    /**如果下一个标本，则清空中间结果 */
    clearPatResultInfos();
    /**数据为空的时候，清除历史结果*/
    generalReviewRef.value?.cleanData(null);
    return;
  }
  //mainInfoData = row;

  if (generalReviewRef.value) {
    isDot.value = false;
    generalReviewRef.value?.getHisResultDot(row);
    if (!IsEmpty(rightTabValue.value) && `${rightTabValue.value}` === '2') {
      generalReviewRef.value?.getResultReview(row);
      generalReviewRef.value?.getWidth(patInfoFieldDecimalSize);
    }
  }
  Object.assign(form, row);
  Object.assign(currentMainInfo, row);
  mainInfoEditPanelRef.value?.currentMainInfoChange(row);
  imgTxtRptRef.value?.initPage(row);
  imgSelectRef.value?.initPage(row);
  if (rptResultRef.value) {
    rptResultRef.value?.initTestList(form, isRefreshRptResult); //传递给右侧基本信息表单
    rptResultRef.value?.findFeeVsItemDictCount(form.reqNo, form.rptGroup);
  }
  // imageRef.value?.getImageData(form);
  // costRef.value.getreqDetail(form);

  /**加载危急值已处理数据 */
  getTreatedCriticalReport();
}
/**多条件筛选状态下，列表中没有该项的选中记录，仅仅更新病人信息，中间结果列表 */
function onlyUpdatePatResultInfo(row) {
  if (!row || IsEmpty(row)) {
    return;
  }
  if (generalReviewRef.value) {
    isDot.value = false;
    generalReviewRef.value?.getHisResultDot(row);
    if (!IsEmpty(rightTabValue.value) && `${rightTabValue.value}` === '2') {
      generalReviewRef.value?.getResultReview(row);
      generalReviewRef.value?.getWidth(patInfoFieldDecimalSize);
    }
  }
  Object.assign(form, row);
  Object.assign(currentMainInfo, row);
  mainInfoEditPanelRef.value?.currentMainInfoChange(row);
  imgTxtRptRef.value?.initPage(row);
  imgSelectRef.value?.initPage(row);
  if (rptResultRef.value) {
    rptResultRef.value?.initTestList(form); //传递给右侧基本信息表单
  }
}
/**当检验记录为空时 清空左侧人员信息，中间结果列表数据 */
function clearPatResultInfos() {
  form.id = null;
  //检验记录为空时标本号从1开始
  Object.keys(form).forEach((k) => {
    if (k === 'rptGroup' || k === 'sampleda' || k === 'sampleNo') {
      //ToDo
    } else {
      form[k] = null;
      if (currentMainInfo && currentMainInfo[k]) {
        currentMainInfo[k] = null;
      }
    }
  });
  mainInfoEditPanelRef.value?.currentMainInfoChange(form);
  if (imgTxtRptRef.value) {
    imgTxtRptRef.value?.initPage(form); //传递给右侧基本信息表单
  }
  // imageRef.value?.getImageData(form);
  // costRef.value.getreqDetail(form);
}
/**病人信息修改保存成功回调
 * @row 已修改的检验记录信息
 */
function mainInfoUpdateSuccessCallback(row) {
  if (refFormData.value) {
    refFormData.value?.updateMainInfoRow(row);
  }
}
/**获取模块面板宽度 */
function getmoduleWidth() {
  const url = '/lab/wlConfig/findWlConfigSizeAndHeight';
  const data = {
    suitModule: '1',
    rptGroup: form.rptGroup
  };
  proxy.$http
    .get(url, { params: data })
    .then((res: any) => {
      if (res.data !== null) {
        // patInfoPanelSize.value = res.data.patsPanelSize * 100;
        // resultSize.value = res.data.resultsPanelSize * 100;
        // patInfoFieldSize.value = 100 - patInfoPanelSize.value - resultSize.value;
        patInfoFieldDecimalSize = res.data.workbenchPanelSize;
        rptResultRef.value.resultRowHeight(res.data.resultRowHeight);
        refFormData.value.wlRowHeight(res.data.wlRowHeight);
      } else {
        // patInfoPanelSize.value = 20;
        // resultSize.value = 35;
        // patInfoFieldSize.value = 45;
        patInfoFieldDecimalSize = 0.45;
        rptResultRef.value.resultRowHeight(24);
        refFormData.value.wlRowHeight(24);
      }
    })
    .catch((err: any) => {});
}
/**检验报告结果返回 */
function rptResultList(val: any[]) {
  //检验报告结果返回
  if (refFormData.value && val && val.length > 0 && !IsEmpty(val[0].maininfoId)) {
    refFormData.value?.refreshMainInfoListM4(val[0].maininfoId);
  }
}

/**
 * 【没有上机记录的情况下】
 * 直接添加检验结果/编辑病人信息等成功后
 * 刷新上机记录列表并刷新中间结果列表
 * @isSelCurRow 是否选中检验记录当前行
 * @isRefreshRptResult 是否刷新中间结果列表
 */
function updateTestList({ isSelCurRow, isRefreshRptResult, mainInfoId }) {
  refFormData.value?.refreshMainInfoListM2({ isSelCurRow, isRefreshRptResult, mainInfoId });
}

function pushTemplate() {
  if (refFormData.value) {
    refFormData.value?.toggleItemTemplatePanel();
  }
  isShowItemTemplatePanel.value = !isShowItemTemplatePanel.value;
  if (isShowItemTemplatePanel.value) {
    mainInfoTopPanel.value = 70;
  } else {
    mainInfoTopPanel.value = 100;
  }
  loadMItemplateData(); /**加载模板数据 */
}

const findList = () => {
  loading.value = true;
  tableData.value = [];
  setTimeout(() => {
    const list = [];
    tableData.value = list;
    loading.value = false;
  }, 500);
};

const contextMenuClickEvent: VxeTableEvents.MenuClick<RowVO> = ({ menu, row, column }) => {
  const $table = tableRef.value;
  if ($table) {
    switch (menu.code) {
      case 'hideColumn':
        $table.hideColumn(column);
        break;
      case 'showAllColumn':
        $table.resetColumn(true);
        break;
      case 'copy':
        if (XEClipboard.copy((row as any)[column.field])) {
          VXETable.modal.message({ content: '已复制到剪贴板！', status: 'success' });
        }
        break;
      case 'reload':
        findList();
        break;
      case 'insertAt':
        $table.insertAt({}, row || -1).then(({ row }) => {
          $table.setEditCell(row, column || 'name');
        });
        break;
      case 'remove':
        $table.remove(row);
        break;
      case 'save':
        VXETable.modal.message({ content: '保存成功', status: 'success' });
        findList();
        break;
    }
  }
};

const getInsertEvent = () => {
  const $table = tableRef.value;
  if ($table) {
    const insertRecords = $table.getInsertRecords();
    VXETable.modal.alert(insertRecords.length);
  }
};

const getRemoveEvent = () => {
  const $table = tableRef.value;
  if ($table) {
    const removeRecords = $table.getRemoveRecords();
    VXETable.modal.alert(removeRecords.length);
  }
};

const getUpdateEvent = () => {
  const $table = tableRef.value;
  if ($table) {
    const updateRecords = $table.getUpdateRecords();
    VXETable.modal.alert(updateRecords.length);
  }
};

function getIsDot(val: any) {
  if (val !== null) {
    isDot.value = val;
  }
}

function getResultTemplate(resultTemplateId) {
  if (!IsEmpty(form.isChk) && form.isChk >= 1) {
    VxeMessage('已审核', VxeNotifyType.warning);
    return;
  }
  const params = {
    templateId: resultTemplateId,
    sampleda: form.sampleda,
    sampleNo: form.sampleNo,
    rptGroup: form.rptGroup,
    maininfoId: form.id
  };

  const url = '/lab/template/batchInsertTemplateList';
  proxy.$http
    .post(url, params)
    .then((res: any) => {
      if (res.data && res.data.length > 0) {
        rptResultRef.value.getModuleResultList(res.data, resultTemplateId);
      }
      // if (res && res.status && !IsEmpty(res.status.code) && res.status.code === 1 && refFormData.value && res.data && !IsEmpty(res.data.id)) {
      //   refFormData.value?.refreshMainInfoListM2({ isSelCurRow: true, isRefreshRptResult: true, mainInfoId: res.data.id });
      // }
    })
    .catch((err: any) => {
      VxeMessage(err, VxeNotifyType.error);
    });
}

function repSelectChange(value) {
  //console.log(value, '90909090909');
}

let refFormData: any = ref(null); //回车标本号新增数据
//向TestList子组件传递表单值
function handleSearchByCode({ value, $event }: any) {
  if ($event.keyCode === 13) {
    /**如果是条件筛选状态下，直接跳转下一个标本 */
    if (refFormData.value) {
      const m = refFormData.value?.isMultiFilterState();
      if (m) {
        const cl = refFormData.value?.getCurrentRecordList();
        const r = refFormData.value?.getCurrentRecordRow();
        if (cl && cl.length > 0) {
          if (!IsEmpty(r.id)) {
            if (cl[cl.length - 1].id != r.id) {
              refFormData.value?.nextRowSelected(r);
              return;
            }
          }
        }
      }
    }

    form.reqNo = '';
    refFormData.value?.baseInfoChange(3, value, form, async () => {
      //#region  Name
      if (true) {
        /**没有选中，查询数据库，是否是否有该条记录 */
        const res = await refFormData.value?.findLabMainInfoByPrimaryData(form.rptGroup, form.sampleda, form.sampleNo);
        if (res && res.length > 0) {
          Object.assign(form, res[0]);
          Object.assign(currentMainInfo, res[0]);
          mainInfoEditPanelRef.value?.currentMainInfoChange(res[0]);
          if (rptResultRef.value) {
            rptResultRef.value?.initTestList(form, false); //传递给右侧基本信息表单
          }
        }
        if (!res) {
          /**如果下一个标本，则清空中间结果 */
          clearPatResultInfos();
        }
      }
      //#endregion
    });
    reqNoInput.value?.focus();
  }
}

function handleSearchByReqno({ value, $event }: any) {
  if ($event.keyCode === 13) {
    if (!isEmpty(value)) {
      form.reqNo = value;
    }
    refFormData.value?.baseInfoChange(4, value, form, (e) => {
      if (e && e.isnextcode === false) {
        return;
      }
      const a = getOptionValueByCodeRptGroupOption('smhzdxygbb');
      if (a && (a === '1' || a === 1)) {
        $this['nextCode']();
      } else {
        //选中最后一条
        refFormData.value?.waitSelectCurrentRow(form, value, null);
      }
    });
    return;
  }
}
//传值到RptResult.vue界面
function reqRptResult(val: any) {
  if (val !== null) {
    Object.assign(form, val);
    // imageRef.value?.getImageData(form);
    // costRef.value.getreqDetail(form);
    //rptResultRef.value.initTestList(form); //传递给右侧基本信息表单
    imgTxtRptRef.value?.initPage(form);
  } else {
    /**下一个标本，需要清空中间的结果 */
    form.id = null;
    // imageRef.value?.getImageData(form);
    // costRef.value.getreqDetail(form);
    //rptResultRef.value.initTestList(form); //传递给右侧基本信息表单
    imgTxtRptRef.value?.initPage(form);
  }
}
//传值到父
function labMainInfoList(val: any) {
  scanCodeForm.wl = val;
}
//传值到父-让列表刷新
function refreshLabMinInfo(val: any) {
  refFormData.value.initPage(form);
}

//传值到Template.vue界面
function templateClick(e) {
  repetitionRef.value.maininfoIdChange(form.id);
  templateRef.value.initRptGroup(form); //传递给右侧基本信息表单
  //sampleReturnRef.value.getSample(form);
  LabMainInfoLogRef.value.initForm(form);
  if (generalReviewRef.value && !IsEmpty(e.index) && `${e.index}` === '2') {
    isDot.value = false;
    generalReviewRef.value?.getHisResultDot(form);
    generalReviewRef.value?.getResultReview(form);
    generalReviewRef.value?.getWidth(patInfoFieldDecimalSize);
  }
}
//点击设置打开信息设置页面
function wkltConfig() {
  wkltConfigForm.visible = true;
  wkltConfigRef.value?.wkltConfigData(wkltConfigForm);
}

/**
 * 审核确认
 * @e
 */
function chkConfirm(e) {
  /**只修改当前标本 e.edtType===1*/
  /**修改所有未审核标本 e.edtType===2*/
  /**修改指定标本号范围 e.edtType===3*/
  refFormData.value?.refreshMainInfoListM3(e);

  /** 如果是打印前自动审核，审核后，需要判断下是否跳转下一个标本*/
  if (chkBeforePrint.value) {
    isNextMainInfoSelection();
  }
}

/**左侧修改病人信息 检测医生 审核医生验证成功后调用 */
function validateTestChkDoctorSuccess(e) {
  /**只修改当前标本 e.edtType===1*/
  /**修改所有未审核标本 e.edtType===2*/
  /**修改指定标本号范围 e.edtType===3*/
  refFormData.value?.refreshMainInfoListM3(e, false, false);
}

//#region  检验记录
function actionCLick(item) {
  console.log(item.event);

  if ($this[item.event]) {
    if (item.event == 'chkMainInfo') {
      $this[item.event](item);
    } else {
      $this[item.event]();
    }
  }
  //调用自己的接口
  if (item.getContent == 'getWlEhrName') {
    const url = '/api/sys/hisEmployee/getInterfaceData';
    const params = {
      url: (window as any).apiUrl.VUE_APP_INTERFACE_URL + '/EHR/getEHRByIdNo',
      code: 'GET_EHR',
      idNo: form.idNo
    };
    proxy.$http
      .get(url, { params: params })
      .then((res: any) => {
        window.open(JSON.parse(res.data).data);
      })
      .catch((err: any) => {
        VxeMessage('同步失败', VxeNotifyType.error);
      });
  }
}
let reportList = reactive([]);
//预览方法
$this['previewRpt'] = () => {
  isPreviewRpt.value = false;
  reportList.length = 0;
  if (IsEmpty(form)) {
    VxeMessage('预览失败', VxeNotifyType.error);
  }
  proxy.$http
    .post('/lab/maininfo/previewRpt', form)
    .then((res: any) => {
      Object.assign(reportList, res.data);
      isPreviewRpt.value = true;
    })
    .catch((err: any) => {
      VxeMessage('预览失败', VxeNotifyType.error);
    });
};

//新增一条mianinfo主表记录
const addMaininfoByReqNo= () => {
    const url = '/lab/rptResult/addMaininfoByReqNo';
    proxy.$http
      .get(url, {
        params: {
        reqNo: form.reqNo,
        rptGroup: form.rptGroup,
        sampleda: form.sampleda+" 00:00:00",
        sampleNo: form.sampleNo
        }
      })
      .then((res: any) => {
        if (res && res.status.code === 1
          && res.data) {
          updateTestList({
            isSelCurRow: true,
            isRefreshRptResult: false,
            mainInfoId: res.data.id });
        }

      })
      .catch((err: any) => {
      });
};
/**
 * 下一个
 * @isCallMainInfo 是否调用检验列表组件
 * 默认值 true
 * 当条码号回车时，不调用只标本号+1即可
 * */
$this['nextCode'] = (isCallMainInfo = true) => {
  /**如果是条件筛选状态下，直接跳转下一个标本 */
  // if (refFormData.value) {
  //   const m = refFormData.value?.isMultiFilterState();
  //   if (m) {
  //     const cl = refFormData.value?.getCurrentRecordList();
  //     const r = refFormData.value?.getCurrentRecordRow();
  //     if (cl && cl.length > 0) {
  //       if (!r && !IsEmpty(r) && !IsEmpty(r.id)) {
  //         if (cl[cl.length - 1].id != r.id) {
  //           refFormData.value?.nextRowSelected(r);
  //           return;
  //         }
  //       }
  //     }
  //   }
  // }

  const a = autoIncrementNumber(form.sampleNo, '+');
  form.sampleNo = a;
  form.reqNo = '';
  if (isCallMainInfo) {
    refFormData.value?.baseInfoChange(3, a, form, async () => {
      //#region  Name
      if (true) {
        /**没有选中，查询数据库，是否是否有该条记录 */
        const res = await refFormData.value?.findLabMainInfoByPrimaryData(form.rptGroup, form.sampleda, form.sampleNo);
        if (res && res.length > 0) {
          Object.assign(form, res[0]);
          Object.assign(currentMainInfo, res[0]);
          mainInfoEditPanelRef.value?.currentMainInfoChange(res[0]);
          //imgTxtRptRef.value?.initPage(form);
        }
        if (!res) {
          /**如果下一个标本，则清空中间结果 */
          //clearPatResultInfos();
          //getResultTemplate();
          //imgTxtRptRef.value?.initPage(form);
          //没有查询到，则新增一条mianinfo主表记录
          //addMaininfoByReqNo();
        }
      }
      //#endregion
    });
  }
};

function auditGetNextRow() {
  $this['nextCode']();
}

/**
 *上一个
 * @isCallMainInfo 是否调用检验列表组件
 * 默认值 true
 * 当条码号回车时，不调用只标本号+1即可
 * */
$this['prevCode'] = (isCallMainInfo = true) => {
  /**如果是条件筛选状态下，直接跳转上一个标本 */
  // if (refFormData.value) {
  //   const m = refFormData.value?.isMultiFilterState();

  //   if (m) {
  //     const cl = refFormData.value?.getCurrentRecordList();
  //     const r = refFormData.value?.getCurrentRecordRow();
  //     if (cl && cl.length > 0) {
  //       if (!r && !IsEmpty(r) && !IsEmpty(r.id)) {
  //         if (cl[0].id != r.id) {
  //           refFormData.value?.nextRowSelected(r, 'u');
  //           return;
  //         }
  //       }
  //     }
  //   }
  // }
  const a = autoIncrementNumber(form.sampleNo, '-');
  form.sampleNo = a;
  form.reqNo = '';
  if (isCallMainInfo) {
    refFormData.value?.baseInfoChange(3, a, form, async () => {
      //#region  Name
      if (true) {
        /**没有选中，查询数据库，是否是否有该条记录 */
        const res = await refFormData.value?.findLabMainInfoByPrimaryData(form.rptGroup, form.sampleda, form.sampleNo);
        if (res && res.length > 0) {
          Object.assign(form, res[0]);
          Object.assign(currentMainInfo, res[0]);
          mainInfoEditPanelRef.value?.currentMainInfoChange(res[0]);
          if (imgTxtRptRef.value) {
           //imgTxtRptRef.value?.initPage(form)
          }
        }
        if (!res) {
          /**如果下一个标本，则清空中间结果 */
         //imgTxtRptRef.value?.initPage(form)
        }
      }
      //#endregion
    });
  }
};

//刷新报告项目
$this['handleSearch'] = () => {
  imgTxtRptRef.value?.initPage(form);
};


//批量扫码
$this['scanCodeBulk'] = () => {
  scanCodeForm.rptGroup = form.rptGroup;
  scanCodeForm.sampleNo = form.sampleNo;
  scanCodeForm.sampleda = form.sampleda;
  scanCodeForm.visible = true;
  scanCodeDlgRef.value?.wkltData(scanCodeForm);
  proxy.$nextTick(() => {
    scanCodeDlgRef.value?.focus();
  });
};

//复查
$this['setRepetition'] = () => {
  if (!IsEmpty(form.isChk) && form.isChk >= 1) {
    VxeMessage('已审核', VxeNotifyType.warning);
    return;
  }
  if (rptResultRef.value) {
    rptResultRef.value.setRepetition();
  }
};
/**
 * 审核后立即打印调用
 * @mainInfo 需要打印的报告
 */
function printAfterChk(mainInfo) {
  if (IsEmpty(mainInfo)) {
    return;
  }
  printAction();
}
//打印报告
$this['previewPrint'] = async () => {
  /**先把打印前的自动审核标记置为fasle */
  chkBeforePrint.value = false;
  alarmReportBeforeChk.value = false;
  if (!rptResultRef.value?.printValidateVsCountIsEqual()) {
    return;
  }

  /** 打印前必须审核*/
  const a = getOptionValueByCodeRptGroupOption('dyqbxsh');
  const row = refFormData.value?.getCurrentRecordRow();
  if ((a === '1' || a === 1) && row.isChk < 2) {
    if (refFormData.value) {
      //const row = refFormData.value?.getCurrentRecordRow();
      /**打印前自动审核系统选项 */
      const b = getOptionValueByCodeRptGroupOption('dyqzdsh');
      /**【情况一】 打印时不自动审核且改行未审核，提示先审核数据*/
      if (row.isChk < 2 && b !== '1' && b !== 1) {
        VxeMessage('请先审核数据', VxeNotifyType.warning);
        return;
      }
      /** 审核完自动打印*/
      const c = getOptionValueByCodeRptGroupOption('shhzddy');
      /**【情况二】未审核，打印时自动审核,审核后自动打印 */
      if (row.isChk < 2 && (b === '1' || b === 1) /*打印时，未审核，自动审核*/ && (c === '1' || c === 1) /*审核后，自动打印*/) {
        /**先走审核逻辑,不用再走打印 */

        //1、验证审核时 是否弹出危急值上报界面
        //审核时是否弹出危急值上报界面
        const aalarm = getOptionValueByCodeGlobalOption('shstcwjzsbjm'); /**审核时是否弹出危急值界面 shstcwjzsbjm*/

        if (aalarm === '1' || aalarm === 1) {
          if (refFormData.value) {
            const rowMI = refFormData.value?.getCurrentRecordRow();
            if (rowMI && !IsEmpty(rowMI.id) && !IsEmpty(rowMI.isAlarm) && (rowMI.isAlarm === '1' || rowMI.isAlarm === 1)) {
              //是否还有未处理的危急值
              const criNotreat = await isNotreatAlarmReport(rowMI.rptGroup, rowMI.sampleda, rowMI.sampleNo);
              if (criticalReportRef.value && criNotreat) {
                alarmReportBeforeChk.value = true;
                chkBeforePrint.value = true;
                criticalReportRef.value?.criticaReportData(rowMI);
                return;
              }
            }
          }
        }

        //2、缓存中，检验医师、审核医师没有过期 则使用缓存中的数据
        if (storeObj.chkDoctorObj && !IsEmpty(storeObj.chkDoctorObj.code)) {
          const curDateTime = new Date().valueOf();
          if (Number(curDateTime) > Number(storeObj.chkDoctorObj.expressin)) {
            if (ChkAuthCompRef.value) {
              ChkAuthCompRef.value?.initPage(true, '审核');
            }
            chkBeforePrint.value = true;
            return;
          }
        } else {
          if (ChkAuthCompRef.value) {
            ChkAuthCompRef.value?.initPage(true, '审核');
          }
          chkBeforePrint.value = true;
          return;
        }

        let resData = { edtType: 1, codeRange: '', action: '2' };
        if (refFormData.value) {
          refFormData.value?.refreshMainInfoListM3(resData);
        }

        /**再判断是否跳转选中下一个标本 */
        /**判断审核后是否自动跳转下一个标本 【shtgzdxybb】*/
        const d = getOptionValueByCodeRptGroupOption('shtgzdxybb');
        /**审核后自动跳转下一个标本，则跳转下一个标本不再执行 */
        if (d === '1' || d === 1) {
          return;
        }

        /**审核后【不】自动跳转下一个标本，则继续执行打印后跳转下一个标本 */
        const e = getOptionValueByCodeRptGroupOption('dyhzdxybb');
        if (e === '1' && e === 1) {
          //跳转下一个标本
          selectNextMainInfoRo();
          return;
        }
      }

      /**【情况三】未审核，打印时自动审核,审核后【不】自动打印 */
      if (row.isChk < 2 && (b === '1' || b === 1) /*打印时，未审核，自动审核*/ && c !== '1' && c !== 1 /*审核后，【不】自动打印*/) {
        /**先走审核逻辑 */
        //1、验证审核时 是否弹出危急值上报界面
        //审核时是否弹出危急值上报界面
        const aalarm = getOptionValueByCodeGlobalOption('shstcwjzsbjm'); /**审核时是否弹出危急值界面 shstcwjzsbjm*/

        if (aalarm === '1' || aalarm === 1) {
          if (refFormData.value) {
            const rowMI = refFormData.value?.getCurrentRecordRow();
            if (rowMI && !IsEmpty(rowMI.id) && !IsEmpty(rowMI.isAlarm) && (rowMI.isAlarm === '1' || rowMI.isAlarm === 1)) {
              //是否还有未处理的危急值
              const criNotreat = await isNotreatAlarmReport(rowMI.rptGroup, rowMI.sampleda, rowMI.sampleNo);
              if (criticalReportRef.value && criNotreat) {
                alarmReportBeforeChk.value = true;
                chkBeforePrint.value = true;
                criticalReportRef.value?.criticaReportData(rowMI);
                return;
              }
            }
          }
        }

        //2、缓存中，检验医师、审核医师没有过期 则使用缓存中的数据
        if (storeObj.chkDoctorObj && !IsEmpty(storeObj.chkDoctorObj.code)) {
          const curDateTime = new Date().valueOf();
          if (Number(curDateTime) > Number(storeObj.chkDoctorObj.expressin)) {
            if (ChkAuthCompRef.value) {
              ChkAuthCompRef.value?.initPage(true, '审核');
            }
            chkBeforePrint.value = true;
            return;
          }
        } else {
          if (ChkAuthCompRef.value) {
            ChkAuthCompRef.value?.initPage(true, '审核');
          }
          chkBeforePrint.value = true;
          return;
        }

        let resData = { edtType: 1, codeRange: '', action: '2' };
        if (refFormData.value) {
          refFormData.value?.refreshMainInfoListM3(resData);
        }
        /**再走打印处理 */
        printAction();

        /**最后判断是否跳转选中下一个标本 */
        /**判断审核后是否自动跳转下一个标本 【shtgzdxybb】*/
        const d = getOptionValueByCodeRptGroupOption('shtgzdxybb');
        /**审核后自动跳转下一个标本，则跳转下一个标本不再执行 */
        if (d === '1' || d === 1) {
          return;
        }

        /**审核后【不】自动跳转下一个标本，则继续执行打印后跳转下一个标本 */
        const e = getOptionValueByCodeRptGroupOption('dyhzdxybb');
        if (e === '1' && e === 1) {
          //跳转下一个标本
          selectNextMainInfoRo();
          return;
        }
      }
    }
    return;
  }
  /**打印前不必审核 */
  printAction();

  /**打印后跳转下一个标本 */
  const e = getOptionValueByCodeRptGroupOption('dyhzdxybb');
  if (e === '1' || e === 1) {
    //跳转下一个标本
    selectNextMainInfoRo();
    return;
  }
};

/**
 * 判断是否跳转下一个标本选中
 * 打印时自动审核会用到
 * 因为打印时 如果自动审核
 * 有可能先弹出密码校验
 * 校验完成后会走审核
 * 审核完成后 不走自动下一个
 * 打印后自动下一个参数起作用时会用此函数
 * */
function isNextMainInfoSelection() {
  chkBeforePrint.value = false;
  /**再判断是否跳转选中下一个标本 */
  /**判断审核后是否自动跳转下一个标本 【shtgzdxybb】*/
  const d = getOptionValueByCodeRptGroupOption('shtgzdxybb');
  /**审核后自动跳转下一个标本，则跳转下一个标本不再执行 */
  if (d === '1' || d === 1) {
    return;
  }

  /**审核后【不】自动跳转下一个标本，则继续执行打印后跳转下一个标本 */
  const e = getOptionValueByCodeRptGroupOption('dyhzdxybb');
  if (e === '1' && e === 1) {
    //跳转下一个标本
    selectNextMainInfoRo();
    return;
  }
}

/**
 * 跳转检验记录下一个标本的计算
 */
function selectNextMainInfoRo() {
  if (refFormData.value) {
    const row = refFormData.value?.getCurrentRecordRow();
    refFormData.value?.nextRowSelected(row);
  }
}

/**
 * 仅负责打印处理,不判断参数控制
 * @mainInfo 需要打印的上机记录
 */
function printAction(mainInfo) {
  const rowCurrent = refFormData.value?.getCurrentRecordRow();
  if (rowCurrent === null || rowCurrent === undefined || IsEmpty(rowCurrent) || IsEmpty(rowCurrent.id)) {
    return;
  }
  const islocserstart = sessionStorage.getItem('locserstart');
  if (!islocserstart || IsEmpty(islocserstart)) {
    VxeMessage('本地服务未打开', VxeNotifyType.error);
    return;
  }
  const url = '/lab/maininfo/LabMainInfoPrint';
  proxy.$http
    .post(url, rowCurrent)
    .then((res: any) => {
      refFormData.value?.refreshMainInfoListM4(rowCurrent.id);
      let arr = [];
      res.data.forEach((e) => {
        arr.push({ ReportName: e.reportId, ReportParameters: [{ Name: 'Id', Value: e.id }], PdfPrinterSetting: { PdfPrinterCopies: 1 } });
      });
      printParamsObj.value = arr; //[{ ReportName: '1759924571139497986', ReportParameters: [{ Name: 'Id', Value: '123' }], PdfPrinterSetting: { PdfPrinterCopies: 1 } }]; // { id: new Date().valueOf(), params: ['123', '345', '567'] };
    })
    .catch((err: any) => {
      VxeMessage('打印失败', VxeNotifyType.error);
    });
}

//危急值
$this['openRptCriticalValue'] = () => {
  //mainInfoData.rptGroup = wkltConfigForm.rptGroupName;
  form.rptGroup = wkltConfigForm.rptGroup;
  criticalReportRef.value?.criticaReportData(form);
};

/**检查是否有未处理的危急值 */
function isNotreatAlarmReport(rptGroup, sampleda, sampleNo) {
  return new Promise((resolve, reject) => {
    const url = '/lab/rptResult/getAlarmResult';
    proxy.$http
      .get(url, { params: { rptGroup: rptGroup, sampleda: sampleda, sampleNo: sampleNo } })
      .then((res: any) => {
        if (res && res.data && res.data.length > 0) {
          resolve(true);
        } else {
          resolve(false);
        }
      })
      .catch((err) => {
        resolve(false);
      });
  });
}

/**危急值处理完成 */
function alarmTreatFinish() {
  if (alarmReportBeforeChk.value && !chkBeforePrint.value) {
    $this['chkMainInfo']();
  }
  if (alarmReportBeforeChk.value && chkBeforePrint.value) {
    $this['previewPrint']();
  }
}

/**初审 */
/**取消初审 */
/** 审核 */
$this['chkMainInfo'] = async (item: any) => {
  if (!imgTxtRptRef.value?.reviewValidateVsCountIsEqual()) {
    return;
  }

  alarmReportBeforeChk.value = false; /**审核前,上报危急值弹窗 */
  //审核时是否弹出危急值上报界面
  const a = getOptionValueByCodeGlobalOption('shstcwjzsbjm'); /**审核时是否弹出危急值界面 shstcwjzsbjm*/

  if (a === '1' || a === 1) {
    if (refFormData.value) {
      const row = refFormData.value?.getCurrentRecordRow();
      if (row && !IsEmpty(row.id) && !IsEmpty(row.isAlarm) && (row.isAlarm === '1' || row.isAlarm === 1)) {
        //是否还有未处理的危急值
        const criNotreat = await isNotreatAlarmReport(row.rptGroup, row.sampleda, row.sampleNo);
        if (criticalReportRef.value && criNotreat) {
          alarmReportBeforeChk.value = true;
          criticalReportRef.value?.criticaReportData(row);
          return;
        }
      }
    }
  }

  //缓存中，检验医师、审核医师没有过期 则使用缓存中的数据
  if (storeObj.chkDoctorObj) {
    const curDateTime = new Date().valueOf();
    if (Number(curDateTime) > Number(storeObj.chkDoctorObj.expressin)) {
      if (ChkAuthCompRef.value) {
        ChkAuthCompRef.value?.initPage(true, item.content);
      }
      storeObj.clearChkDoctorObj();
      return;
    }
    let resData = { edtType: 1, codeRange: '', action: '2' };
    if (item && item.content == '初审') {
      resData = { edtType: 1, codeRange: '', action: '1' };
    }
    if (refFormData.value) {
      refFormData.value?.refreshMainInfoListM3(resData);
    }
    return;
  }
  if (ChkAuthCompRef.value) {
    ChkAuthCompRef.value?.initPage(true, item.content);
  }
};

/**
 * 取消审核
 */
$this['unChkMainInfo'] = () => {
  /**消审操作人需再登录 xsczrxyzdl */
  const a = getOptionValueByCodeGlobalOption('xsczrxyzdl'); /**消审操作人需再登录 xsczrxyzdl*/
  if (a && (a === '1' || a === 1)) {
    if (AuthValidateCompRef.value) {
      AuthValidateCompRef.value?.initPage(true, '取消审核验证');
      return;
    }
  }

  /**取消审核必须选择取消审核原因 qxshbxxzqxshyy */
  const b = getOptionValueByCodeGlobalOption('qxshbxxzqxshyy'); /**取消审核必须选择取消审核原因 qxshbxxzqxshyy*/
  if (b && (b === '1' || b === 1)) {
    if (LabMainInfoUnChkReasonRef.value) {
      LabMainInfoUnChkReasonRef.value?.initPage();
      return;
    }
  }

  if (refFormData.value) {
    refFormData.value?.unChkMainInfo(currentMainInfo);
  }
};

/**取消审核弹窗  确定选择后调用 */
function confirmSelectReasonCallback(arr, isincintoqi = 1) {
  const a = 'isIncintoQi';
  const b = 'unChkDoctor';
  const b1 = 'unChkDoctorNa';
  const c = 'unchkTime';
  const d = 'unchkReason';
  currentMainInfo[a] = isincintoqi;
  const e = localStorage.getItem('userInfo');
  const f = JSON.parse(e);
  currentMainInfo[b] = f && !IsEmpty(f.username) ? f.username : '';
  currentMainInfo[b1] = f && !IsEmpty(f.realname) ? f.realname : '';
  currentMainInfo[c] = formatDateTime(new Date(), 'yyyy-MM-dd hh:mm:ss');
  const g = 'cancleAuditList';
  currentMainInfo[g] = arr;
  let arrStr = [];
  arr.forEach((ele) => {
    if (!IsEmpty(ele.reason)) {
      arrStr.push(ele.reason);
    }
  });
  let strReason = arrStr.join(',');
  currentMainInfo[d] = strReason;
  if (refFormData.value) {
    refFormData.value?.unChkMainInfo(currentMainInfo);
  }
}

/**取消审核验证成功返回 */
function unChkConfirm(e) {
  if (refFormData.value) {
    refFormData.value?.unChkMainInfo(currentMainInfo, e);
  }
}

/**
 * 切换项目模板显示
 */
$this['showTemplate'] = () => {
  if (refFormData.value) {
    refFormData.value?.toggleItemTemplatePanel();
  }
  isShowItemTemplatePanel.value = !isShowItemTemplatePanel.value;
  if (isShowItemTemplatePanel.value) {
    mainInfoTopPanel.value = 70;
  } else {
    mainInfoTopPanel.value = 100;
  }
  loadMItemplateData(); /**加载模板数据 */
  rightTabValue.value = '3';
};

/**
 * 加载显示检验记录下方的输入模板数据
 */
function loadMItemplateData() {
  if (!miTemplateRef.value) {
    setTimeout(() => {
      loadMItemplateData();
    }, 500);
    return;
  }
  if (miTemplateRef.value) {
    miTemplateRef.value?.initRptGroup(form);
  }
  if (LabMainInfoLogRef.value) {
    LabMainInfoLogRef.value.initForm(form);
  }
}

/**提示存在危急值
 *
 */
function tipsAlarmExist() {
  isTipsExistAlarm.value = false;
  const url = '/lab/rptResult/getAlarmExistsByMainInfoIds';
  let data = [];
  if (refFormData.value) {
    const list = refFormData.value?.getCurrentRecordList();
    if (list.length > 0) {
      const arr = list.filter((p) => p.isAlarm === 1);
      arr.forEach((itm) => {
        data.push(itm.id);
      });
    }
  }
  if (data && data.length <= 0) {
    isTipsExistAlarm.value = false;
    return;
  }
  proxy.$http
    .post(url, data)
    .then((res: any) => {
      if (res && res.status && res.status.code === 1 && res.data && res.data.length > 0) {
        isTipsExistAlarm.value = true;
      } else {
        isTipsExistAlarm.value = false;
      }
    })
    .catch((err: any) => {
      isTipsExistAlarm.value = false;
    });
}

// 下拉报告单元获取报告单元id
function getSelectedId(selectedRadioId, selectedName) {
  //fixme:尝试写死报告单元
  selectedRadioId.value = 'GSBG';
  selectedName.value = 'GSBG-骨髓报告';
  GetRptGroupOptions(selectedRadioId.value);
  form.id = '';
  form.rptGroup = selectedRadioId.value;
  form.reqNo = '';
  form.sampleNo = '1';
  wkltConfigForm.rptGroup = selectedRadioId.value;
  wkltConfigForm.rptGroupName = selectedName.value;
  getmoduleWidth();
  mainInfoEditPanelRef.value.getWkltConfigList(form.rptGroup);
  //rptResultRef.value.getResultConfigList(form.rptGroup);
    console.log('getSelectedId------------------');

  refFormData.value.initPage(form);
  templateRef.value.initRptGroup(form);
  miTemplateRef.value.initRptGroup(form);
  //imgTxtRptRef.value?.initPage(form);
  /**【步骤1】将选择的报告单元 放到pinia中**/
  /**【步骤2】查询该报告单元相关的系统参数 例如:未审核报告是否袁旭打印，打印时未审核是否自动审核**/
  /**【步骤3】清空病人信息编辑，中间结果，上机列表,当前选中行**/
  /**【步骤4】请求动态上机列表列，刷新上机列表列顺序**/
  /**【步骤5】请求动态结果列表列，刷新结果列表列顺序**/
  /**【步骤6】请求动态病人信息顺序，刷新病人信息顺序**/
}
/**
 * 检验日期选择发生改变
 */
function timeChange() {
  form.sampleNo = '1';
  form.reqNo = '';
  console.log(form.sampleda, 'form.sampleda');
  const a = formatDateTime(new Date(), 'yyyy-MM-dd');
  const sa = formatDateTime(form.sampleda, 'yyyy-MM-dd');
  console.log(sa, 'form.sa');
  if (a !== sa) {
    notCurDay.value = true;
  } else {
    notCurDay.value = false;
  }
  if (IsEmpty(form.sampleda)) {
    return;
  }
  form.reqNo = '';
  refFormData.value.initPage(form);

  localStorage.setItem('sampleDateNow', sa);

  /**重置全局选择日期时间 Pina  LocalhostSession */

  /**刷新检验记录 */
}
/**条码号输入框回车 有些医院 在中文输入状态下需要切换锁定成 英文状态 需要在此设定 */
function compositionstart() {
  //切换英文状态
}
function refreshFields(refreshFields) {
  if (refreshFields) {
    getmoduleWidth();
  }
}
/**批量扫码，获取检验列表所有行数 */
function getLabMainInfoTableList() {
  const arr = refFormData.value?.getLabMainInfoTableList();
  scanCodeDlgRef.value?.updateLabMaininfoList(arr);
}
//#endregion

//#region  检验结果
/**改变参考范围计算条件后刷新中间结果信息 */
function refreshRptresultsAfterChangeReferConds() {
  rptResultRef.value?.initTestList(form, false); //传递给右侧基本信息表单
}
function refreshRptresultsAfterChangeReferConds1() {
  rptResultRef.value?.initTestList(form, true); //传递给右侧基本信息表单
}

//#endregion

/**查询危急值处理信息 */
function getTreatedCriticalReport() {
  const url = '/lab/criticalReport/getTreatedCriticalReport';
  proxy.$http
    .get(url, { params: { sampleNo: form.sampleNo, rptGroup: form.rptGroup, sampleda: formatDateTime(form.sampleda, 'yyyy-MM-dd hh:mm:ss') } })
    .then((res: any) => {
      if (res && res.status && !IsEmpty(res.status.code) && res.status.code === 1 && res.data && res.data.length > 0) {
        criRptTredList.length = 0;
        Object.assign(criRptTredList, res.data);
        //reviewerTime
        criRptTredList.forEach((m) => {
          m.reviewerTime = formatDateTime(m.reviewerTime, 'yyyy-MM-dd hh:mm');
        });
      }
    })
    .catch((err: any) => {
      //todo
    });
}
</script>
<style lang="scss" scoped>
@import '@/assets/css/el-tabs.scss';

#labmaininfo {
  height: 100%;

  .bodyContent {
    height: calc(100% - 20px);

    .area {
      background-color: $base-white;

      .Splitpanes {
        height: calc(100vh - 110px);
      }

      .lab-maininfo-right-tab {
        height: 100%;

        :deep(.el-tabs__nav-prev) {
          line-height: 28px !important;
        }

        :deep(.el-tabs__nav-next) {
          line-height: 28px !important;
        }

        :deep(.el-tabs__content) {
          height: 100%;
          padding: 2px;
        }

        :deep(.el-tab-pane) {
          height: 100%;
        }
      }
    }
  }
}

:deep(.vxe-form) {
  padding-left: 1px;

  .vxe-input--inner[disabled] {
    color: #000;
  }
}

/**left-bottom-status 左侧底部状态栏工具条样式*/
.left-bottom-status-panel {
  .vxe-toolbar {
    padding: 0.2em 0 !important;
  }
}
</style>
